#include "sound.hpp"

Sound::Sound()
{
	chunk = 0;
};

Sound::~Sound()
{
};

#include "SDL_mixer.h"
#include <iostream>

static Mix_Chunk* ChunkFromText(const std::string & name, char *text, int len)
{
	char *error = NULL;

	SDL_RWops *rwo = SDL_RWFromMem(text, len);
	if(!rwo)
		error = SDL_GetError();

	Mix_Chunk *chunk = NULL;
	if (!error)
	{
		const bool AUTODEL = true;
		chunk = Mix_LoadWAV_RW(rwo, AUTODEL);

		if (!chunk)
			error = Mix_GetError();
	}

	if (error)
	{
		std::cerr << "Sound::Open(" << name << "): " << error;
		std::cerr << std::endl;
	}

	return chunk;
}

#include "disk.hpp"

bool Sound::Open(const std::string & name)
{
	if (chunk)
		return true;

	const char *DIR = "snd/";
	const char *EXT = ".ogg";
	std::string path (DIR);
	path += name;
	path += EXT;

	// SDL_RWops takes only non-const char*
	char *rawtext;
	int len = Dsk.CStrOpen(path, &rawtext);
	if (len <= 0)
		return false;

	chunk = ChunkFromText(name, rawtext, len);
	Dsk.CStrClose(rawtext);

	return chunk != NULL;
}

void Sound::Close()
{
	if (chunk)
		Mix_FreeChunk(chunk);
}

int Sound::Play(int chan, int loop)
{
	return Mix_PlayChannel(chan, chunk, loop);
}

Assets<Sound> AllSnds;
